<template>
<div>
  <div class="search">
      <input type="text" v-model="keyword" class="search-input" placeholder="输入城市名或拼音"/>
  </div>
  <div class="search-content" v-show="this.keyword" ref="search">
    <ul>
      <li v-for="(item, i) in list" :key="i" class="search-item border-bottom" @click="handleCityClick(item.name)">
        {{ item.name }}
      </li>
      <li  class="search-item border-bottom" v-show="hasNoData">
        没有找到匹配数据
      </li>
    </ul>
  </div>
</div>
</template>
<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const key in this.cities) {
          this.cities[key].forEach((item) => {
            if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
              result.push(item)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  padding 0 .1rem
  background $bgColor
  height: 0.72rem
  .search-input
    box-sizing border-box
    width: 100%
    height: .62rem
    text-align center
    color #666
    padding 0 .1rem
    border-radius .1rem
    margin 0
.search-content
  z-index 1
  background-color #eee
  position absolute
  top 1.58rem
  left 0
  right 0
  bottom 0
  .search-item
    line-height .62rem
    padding-left .2rem
    background-color #fff
    color #666
</style>
